package com.example.database.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class MySqlConnector
{
    private Connection conn;


    public  MySqlConnector() throws ClassNotFoundException, SQLException, IOException
    {
        try (InputStream is = this.getClass().getResourceAsStream("/conf/database.properties"))
        {
            Properties pro = new Properties();
            pro.load(is);
            // 从Properties对象中根据键读取值
            String driverClass = pro.getProperty("driver");
            String url = pro.getProperty("url");
            String user = pro.getProperty("user");
            String password = pro.getProperty("password");
            // 1.加载数据库驱动类
            Class.forName(driverClass);
            // 2.创建连接
            conn = DriverManager.getConnection(url, user, password);
        }
    }

    /**
     * 获取连接
     * @return 连接
     */
    public Connection getConnection()
    {
        return conn;
    }

    /**
     * 关闭连接
     * @throws SQLException
     */
    public void closeConnection() throws SQLException
    {
        conn.close();
    }
}
